// 根组件
import { Component } from 'react'
import orderBy from 'lodash/orderBy'

import './index.css'

// 导入子组件
import Tabs from './components/Tabs'
import Form from './components/Form'
import CommentList from './components/CommentList'
import axios from 'axios'

import { Alert } from 'element-react'
const http = axios.create({
  baseURL: 'http://localhost:8888',
})
export default class App extends Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [],
    active: 'hot',
    list: [],
  }
  async componentDidMount() {
    const list = await http.get('/list')
    const tabs = await http.get('/tabs')
    this.setState({
      list: list.data,
      tabs: tabs.data,
    })
  }
  //  切换tab栏
  tabChange = (active) => {
    console.log(active)
    const { list } = this.state
    let newList = []
    if (active === 'hot') {
      // 按照id排序
      newList = orderBy(list, ['id'], ['asc'])
    } else {
      // 按照时间排序
      newList = orderBy(list, ['time'], ['desc'])
    }
    this.setState({
      active,
      list: newList,
    })
  }
  // 添加
  addComment = async (comment) => {
    const { list } = this.state
    const id = Math.max(...list.map((item) => item.id)) + 1 || 0
    console.log(id)
    await http.post('/list', {
      author: '刘德华',
      comment,
      time: new Date('2021-10-10 09:09:00'),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 1,
    })
    this.setState({
      list: [
        {
          id,
          author: '刘德华',
          comment,
          time: new Date('2021-10-10 09:09:00'),
          // 1: 点赞 0：无态度 -1:踩
          attitude: 1,
        },
        ...this.state.list,
      ],
    })
  }
  //  回调删除
  delComment = (id) => {
    http.delete(`/list/${id}`)
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }
  // 点赞或是踩
  changeAttitude = (id, attitude) => {
    http.patch(`/list/${id}`, { attitude })
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            attitude,
          }
        }
        return item
      }),
    })
  }
  render() {
    const { tabs, list, active } = this.state

    return (
      <div className="App">
        <div className="comment-container">
          {/* 评论数 */}
          <div className="comment-head">
            <span>{list.length} 评论</span>
          </div>
          {/* 排序 */}
          <Tabs tabs={tabs} active={active} tabChange={this.tabChange} />

          {/* 添加评论 */}
          <Form
            addComment={
              this.addComment ? (
                <Alert title="添加数据成功" type="success" />
              ) : (
                <Alert title="错误提示的文案" type="error" />
              )
            }
          />

          {/* 评论列表 */}
          <CommentList
            list={list}
            delComment={this.delComment}
            changeAttitude={this.changeAttitude}
          />
        </div>
      </div>
    )
  }
}
